import React, { ChangeEvent, FC, useEffect, useState } from "react";
import styles from "./index.module.scss";
import { Button, Typography, Space, Input, message } from "antd";
import { EditOutlined, LeftOutlined } from "@ant-design/icons";
import { useNavigate, useParams } from "react-router-dom";
import EditToolbar from "../EditToolbar";
import useGetPageInfo from "../../../../hooks/useGetPageInfo";
import { useDispatch } from "react-redux";
import { changePageTitle } from "../../../../store/pageInfoReducer";
import useGetComponentInfo from "../../../../hooks/useGetComponentInfo";
import { useDebounceEffect, useKeyPress, useRequest } from "ahooks";
import { updateQuestionListService } from "../../../../service/questions";
const { Title } = Typography;

//显示和修改标题
const TitleElem: FC = () => {
  const { title } = useGetPageInfo();
  const [editState, setEditState] = useState(false);
  const dispatch = useDispatch();
  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    const newTitle = event.target.value.trim();
    if (newTitle === "") {
      setEditState(false);
      dispatch(changePageTitle(""));
      return;
    }
    dispatch(changePageTitle(newTitle));
  }
  if (editState) {
    return (
      <Input
        value={title}
        onChange={handleChange}
        onProgress={() => setEditState(false)}
        onBlur={() => setEditState(false)}
      />
    );
  }
  return (
    <Space>
      <Title>{title}</Title>
      <Button
        icon={<EditOutlined />}
        type="text"
        onClick={() => setEditState(true)}
      />
    </Space>
  );
};
//保存组件
const SaveButton: FC = () => {
  const { id } = useParams();
  const { componentList = [] } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();

  const { loading, run: save } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionListService(id, { ...pageInfo, componentList });
    },
    {
      manual: true,
    }
  );
  //快捷键
  useKeyPress(["ctrl.s", "meta.s"], (event: KeyboardEvent) => {
    event.preventDefault();
    if (!loading) save();
  });
  //自动保存
  useDebounceEffect(
    () => {
      save();
    },
    [componentList, pageInfo],
    {
      wait: 3000,
    }
  );
  return (
    <Button onClick={save} loading={loading}>
      保存
    </Button>
  );
};
//发布组件
const PublishButton: FC = () => {
  const nav = useNavigate();
  const { id } = useParams();
  const { componentList = [] } = useGetComponentInfo();
  const pageInfo = useGetPageInfo();

  const { loading, run: pub } = useRequest(
    async () => {
      if (!id) return;
      await updateQuestionListService(id, {
        ...pageInfo,
        componentList,
        isPublished: true, //标志问卷已经被发布
      });
    },
    {
      manual: true,
      onSuccess() {
        message.success("发布成功");
        nav("/question/stat/" + id);
      },
    }
  );
  return (
    <Button type="primary" loading={loading} onClick={pub}>
      发布
    </Button>
  );
};
const EditHeader: FC = () => {
  const nav = useNavigate();
  return (
    <div className={styles["header-wrapper"]}>
      <div className={styles.header}>
        <div className={styles.left}>
          <Space>
            <Button type="link" icon={<LeftOutlined />} onClick={() => nav(-1)}>
              返回
            </Button>
            <TitleElem />
          </Space>
        </div>
        <div className={styles.main}>
          <EditToolbar />
        </div>
        <div className={styles.right}>
          <Space>
            <SaveButton />
            <PublishButton />
          </Space>
        </div>
      </div>
    </div>
  );
};

export default EditHeader;
